package com.cskaoyan.mall.controller.mall;

import com.cskaoyan.mall.model.Goods;
import com.cskaoyan.mall.model.Result;
import com.cskaoyan.mall.model.Type;
import com.cskaoyan.mall.model.bo.PlaceOrderBO;
import com.cskaoyan.mall.model.vo.StateOrderVO;
import com.cskaoyan.mall.service.GoodsService;
import com.cskaoyan.mall.service.GoodsServiceImpl;
import com.cskaoyan.mall.service.OrderService;
import com.cskaoyan.mall.service.OrderServiceImpl;
import com.cskaoyan.mall.utils.HttpUtils;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * User: zsquirrel
 * Date: 2020/5/12
 * Time: 6:36 下午
 */
@WebServlet("/api/mall/order/*")
public class OrderServlet extends HttpServlet {

    private OrderService orderService = new OrderServiceImpl();

    private Gson gson = new Gson();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String action = requestURI.replace("/api/mall/order/", "");
        if("addOrder".equals(action)){
            addOrder(request, response);
        }
    }

    private void addOrder(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        PlaceOrderBO placeOrderBO = gson.fromJson(requestBody, PlaceOrderBO.class);
        orderService.placeOrder(placeOrderBO);
        response.getWriter().println(gson.toJson(Result.ok()));
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String action = requestURI.replace("/api/mall/order/", "");
        if("getOrderByState".equals(action)){
            getOrderByState(request, response);
        }
    }

    private void getOrderByState(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String state = request.getParameter("state");
        String token = request.getParameter("token");
        List<StateOrderVO> orderVOList = orderService.getOrderByState(state, token);
        response.getWriter().println(gson.toJson(Result.ok(orderVOList)));
    }

}
